<template>
  <div>
    <!-- <el-row :gutter="20" v-if="isDialog" class="pb-4">
      <el-col :span="24" :xs="24">
        <div class="text-right">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button icon="Refresh" @click="handleReset(form)">重置</el-button>
          <el-button @click="handleReturn(form)">返回</el-button>
        </div>
      </el-col>
    </el-row> -->
    <div :class="isDialog ? '' : 'app-container'">
      <el-row :gutter="20">
        <!--物料分类-->
        <el-col :span="5" :xs="24">
          <el-card :class="isDialog ? 'box-card-dia' : 'box-card'">
            <template #header>
              <div class="font-bold text-16px">
                <el-icon><List /></el-icon><span> 物料分类</span>
                <span class="float-right" v-if="!isDialog">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="新增分类"
                    placement="top-start"
                  >
                    <el-link
                      class="pl-2"
                      icon="Plus"
                      :underline="false"
                      @click="nodeAdd(node, data)"
                    ></el-link
                  ></el-tooltip>
                </span>
              </div>
            </template>

            <el-tree
              ref="avueTree"
              :data="treeData"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children'
              }"
              highlight-current
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node">
                  <a class="node-title" @click.self="nodeClick(data)">
                    {{ node.label }}
                  </a>
                  <span class="text-right node-btn" v-if="!isDialog">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="新增分类"
                      placement="top-start"
                    >
                      <el-link
                        class="pl-2"
                        icon="Plus"
                        :underline="false"
                        @click="nodeAdd(node, data)"
                      ></el-link
                    ></el-tooltip>

                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="编辑分类"
                      placement="top-start"
                      ><el-link
                        class="pl-2"
                        icon="Edit"
                        :underline="false"
                        @click="nodeEdit(data)"
                      ></el-link
                    ></el-tooltip>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="删除分类"
                      placement="top-start"
                      ><el-link
                        class="pl-2"
                        :underline="false"
                        icon="Delete"
                        @click="nodeDel(data)"
                      ></el-link
                    ></el-tooltip>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="下移"
                      placement="top-start"
                      ><el-link
                        class="pl-2"
                        :underline="false"
                        icon="Bottom"
                        @click="nodeDown(data)"
                      ></el-link
                    ></el-tooltip>
                  </span>
                </div>
              </template>
            </el-tree>
          </el-card>
        </el-col>
        <!--物料列表-->
        <el-col :span="19" :xs="24">
          <el-card :class="isDialog ? 'box-card-dia' : 'box-card'">
            <div class="mb6">
              <span v-if="!isDialog">
                <el-button icon="Plus" type="primary" @click="handleAdd"
                  >增加物料</el-button
                >
                <el-button
                  icon="Edit"
                  :disabled="disUpdate"
                  type="primary"
                  plain
                  @click="handleUpdate"
                  >编辑物料</el-button
                >
                <el-button
                  icon="Delete"
                  :disabled="disDel"
                  type="primary"
                  plain
                  v-hasPermi="['productMange:del']"
                  @click="handleDel"
                  >删除物料</el-button
                >
                <!-- <el-button
                  icon="Upload"
                  :disabled="disUpload"
                  type="primary"
                  plain
                  @click="handleUpload"
                  >导入</el-button
                > -->
              </span>
              <div class="inline-block align-top float-right">
                <el-form
                  :model="queryParams"
                  ref="queryRef"
                  :inline="true"
                  label-width="0"
                  @submit.prevent
                >
                  <el-form-item prop="keyword">
                    <el-input
                      v-model="queryParams.keyword"
                      placeholder="输入搜索关键词"
                      clearable
                      style="width: 200px"
                      @keyup.enter="handleQuery"
                      @blur="handleQuery"
                    />
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <el-table
              ref="table"
              v-loading="loading"
              :data="dataList"
              row-key="id"
              :empty-text="emptyText"
              border
              stripe
              current-row-key="id"
              @selection-change="handleSelectionChange"
              @row-click="rowClick"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column prop="name" label="物料名称">
                <template #default="scope" v-if="!isDialog">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="
                      goTo('/source/product/details', {
                        productId: scope.row.id
                      })
                    "
                    >{{ scope.row.name }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column prop="number" label="物料编号" width="150">
              </el-table-column>
              <el-table-column prop="price" label="销售单价" width="80">
                <!-- <template #default="scope">
                <span :value="scope.row.price" />
              </template> -->
              </el-table-column>
              <el-table-column
                prop="specification"
                label="规格型号"
                width="100"
              >
              </el-table-column>
              <el-table-column
                prop="status"
                label="启用状态"
                width="80"
                v-if="!isDialog"
              >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="1"
                    inactive-value="0"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column
                prop="laborService"
                label="是否劳务服务"
                width="100"
                v-if="isDialog"
              >
                <template #default="scope">
                  <dict-drop
                    :options="yes_or_no"
                    :value="scope.row.laborService"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="laborService" label="计量单位" width="100">
                <template #default="scope">
                  <dict-drop
                    :options="measurement_unit"
                    :value="scope.row.unit"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="deviceType"
                label="设备类型"
                width="100"
                v-if="isDialog"
              >
                <template #default="scope">
                  <dict-drop
                    :options="device_type"
                    :value="scope.row.deviceType"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="更新时间"
                align="center"
                prop="updateTime"
                width="160"
                v-if="!isDialog"
              >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="plateType"
                label="板块类型"
                width="150"
                :formatter="plateTypeFormat"
                v-if="!isDialog"
              >
              </el-table-column>
              <!-- <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Select"
                  @click="handleContinue(scope.row)"
                  v-hasPermi="['salesManage:indentManage:continue']"
                  >跟进</el-button
                >
              </template>
            </el-table-column> -->
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              class="mr-4 relative"
              :autoScroll="!isDialog"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              v-model:pageSizes="pageSizes"
              @pagination="getList"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 添加或修改分类对话框 -->
      <el-dialog
        :title="sortBox.title"
        v-model="sortBox.open"
        :width="sortBox.width"
        append-to-body
        @close="cancel"
      >
        <el-form
          ref="sortRef"
          :model="sortForm"
          :rules="sortRules"
          label-width="140px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="分类名称" prop="name">
                <el-input
                  v-model="sortForm.name"
                  placeholder="请输入分类名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="分类编号" prop="number">
                <el-input
                  v-model="sortForm.number"
                  placeholder="请输入分类编号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上级分类" prop="parentId">
                <el-tree-select
                  class="w-full"
                  v-model="sortForm.parentId"
                  :props="{
                    value: 'id',
                    label: 'name',
                    children: 'children'
                  }"
                  value-key="id"
                  :data="sortOptions"
                  placeholder="上级分类"
                  check-strictly
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="板块类型" prop="plateType">
                <el-select
                  class="w-full"
                  v-model="sortForm.plateType"
                  placeholder="板块类型"
                >
                  <el-option
                    v-for="item in ord_product_plate_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产业板块" prop="industrialPlate">
                <el-select
                  class="w-full"
                  v-model="sortForm.industrialPlate"
                  placeholder="产业板块"
                >
                  <el-option
                    v-for="item in ord_product_plate"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="税率" prop="taxRate">
                <el-input v-model="sortForm.taxRate" placeholder="请输入税率" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="享受税收优惠政策" prop="enjoyPreferential">
                <el-radio-group v-model="sortForm.enjoyPreferential">
                  <el-radio
                    v-for="item in yes_or_no"
                    :key="item.value"
                    :label="item.value"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="新物料有效年月" prop="effectiveDate">
                <el-date-picker
                  style="width: 100%"
                  v-model="sortForm.effectiveDate"
                  type="date"
                  placeholder="新物料有效年月"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="收入分摊" prop="incomeShare">
                <el-radio-group v-model="sortForm.incomeShare">
                  <el-radio
                    v-for="item in yes_or_no"
                    :key="item.value"
                    :label="item.value"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="ProductMange">
import { reactive, toRefs, ref } from 'vue'
import {
  listCategory,
  addCategory,
  updateCategory,
  delCategory,
  downCategory,
  listOrdproduct,
  listDiaProduct, //弹窗列表接口
  setOrdproduct,
  delOrdproduct,
  changeProductStatus
} from '@/api/productMange/product'
const props = defineProps({
  productData: {
    type: Object,
    require: false,
    default: () => {
      return {
        isDialog: false
      }
    }
  },
  productQuery: {
    type: Object,
    require: false,
    default: () => {}
  }
})
const isDialog = ref(false)
const emit = defineEmits(['selectionChange'])
const router = useRouter()
const { proxy } = getCurrentInstance()
const {
  device_type,
  ord_product_plate_type,
  ord_product_plate,
  yes_or_no,
  measurement_unit
} = proxy.useDict(
  'device_type',
  'ord_product_plate_type',
  'ord_product_plate',
  'yes_or_no',
  'measurement_unit'
)
const treeData = ref([
  {
    value: 100,
    label: '一级部门',
    children: [
      {
        value: 1,
        label: '一级部门1'
      },
      {
        value: 2,
        label: '一级部门2'
      }
    ]
  },
  {
    value: 3,
    label: '二级部门',
    children: [
      {
        value: 4,
        label: '二级部门1'
      },
      {
        value: 5,
        label: '二级部门2'
      }
    ]
  }
])
const sortOptions = ref([])
const data = reactive({
  loading: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: isDialog.value ? '1' : undefined,
    categoryId: undefined, //物料分类
    keyword: undefined //关键词
  },
  dataList: [],
  emptyText: '暂无数据',
  ids: [],
  selectArr: [],
  total: 0,
  disUpdate: true,
  disDel: true,
  disUpload: false,

  sortBox: {
    title: '新增',
    open: false,
    width: '680px'
  },
  sortForm: {
    sfxsyhzc: 'N'
  },
  sortRules: {
    name: {
      required: true,
      message: '分类名称不能为空',
      trigger: 'blur'
    },
    number: {
      required: true,
      message: '分类编号不能为空',
      trigger: 'blur'
    },
    parentId: {
      required: true,
      message: '上级分类不能为空',
      trigger: 'blur'
    }
  }
})

let {
  loading,
  ids,
  selectArr,
  total,
  queryParams,
  dataList,
  emptyText,
  disUpdate,
  disDel,
  disUpload,
  sortBox,
  sortForm,
  sortRules
} = toRefs(data)
const pageSizes = computed(() =>
  queryParams.value.pageSize === 6 ? [6, 10, 20, 30, 50] : [10, 20, 30, 50]
)
function plateTypeFormat(row, column) {
  return proxy.selectDictLabel(ord_product_plate_type.value, row.plateType)
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
async function init() {
  isDialog.value = props.productData.isDialog
  queryParams.value.status = isDialog.value ? '1' : undefined
  queryParams.value.pageSize = isDialog.value ? 6 : 10
  queryParams.value = { ...queryParams.value, ...props.productQuery }
  await getList()
  getTreeList()
}
/** 搜索按钮操作 */
function handleQuery() {
  //   console.log('检索')
  getList()
}
// 获取数据列表
async function getList() {
  loading.value = true

  if (isDialog.value) {
    try {
      let res = await listDiaProduct(queryParams.value)
      loading.value = false
      dataList.value = res.rows
      total.value = res.total
      // console.log('弹窗列表dataList.value==>', dataList.value)
    } catch (error) {
      // console.log('error==>', error.toString().replace('Error:', ''))
      loading.value = false
      emptyText.value = error.toString().replace('Error:', '')
    }
  } else {
    try {
      let res = await listOrdproduct(queryParams.value)
      console.log('e', res)
      if (res.code !== 200) return
      loading.value = false
      dataList.value = res.rows
      total.value = res.total
      // console.log('列表dataList.value==>', dataList.value)
    } catch (error) {}
  }
}
// 获取数据列表
function getTreeList() {
  listCategory().then(res => {
    treeData.value = res.data //proxy.handleTree(res.data)
    // console.log(' treeData.value==>', treeData.value)
  })
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  console.log('dian')
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDel.value = !selection.length
  emit('selectionChange', selectArr.value)
}
// 单击行
function rowClick(row, column, event) {
  if (!isDialog.value) return
  // 根据id判断当前点击的是否被选中
  const selected = selectArr.value.some(item => item.id === row.id)
  if (!selected) {
    // 选择
    selectArr.value.push(row)
    proxy.$refs.table.toggleRowSelection(row, true)
  } else {
    // 取消
    var finalArr = selectArr.value.filter(item => {
      return item.id !== row.id
    })
    // 取消后剩余选中的
    selectArr.value = finalArr
    proxy.$refs.table.toggleRowSelection(row, false)
  }
}
// 表格行按钮切换
function handleStatusChange(row) {
  console.log('改变', row.status)
  let text = row.status === '0' ? '关闭' : '开启'
  proxy.$modal
    .confirm('确认要' + text + '"' + row.name + '"物料吗?')
    .then(function () {
      return changeProductStatus({ id: row.id, status: row.status })
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

/** 获取分类下拉树结构 */
function getTreeselect() {
  sortOptions.value = []

  let tree = {
    id: 0,
    name: '福建航信物料分类',
    children: treeData.value
  }
  sortOptions.value.push(tree)
  //   console.log('sortOptions.value', sortOptions.value)
}

// 树节点点击
function nodeClick(data) {
  queryParams.value.categoryId = data.id
  getList()
  //   proxy.$message.success(JSON.stringify(data))
}
// 新增分类
function nodeAdd(node, data) {
  getTreeselect()
  sortBox.value.title = '新增'
  sortBox.value.open = true
  sortForm.value.parentId = data.id
  console.log('data==>', data)
}
// 修改分类
function nodeEdit(data) {
  getTreeselect()
  sortBox.value.title = '编辑'
  sortBox.value.open = true
  //   sortForm.value.name = data.name
  //   sortForm.value.number = data.number
  //   sortForm.value.parentId = data.parentId
  //   sortForm.value.id = data.id
  sortForm.value = { ...data }
  //   console.log('data==>', data)
  //   console.log('{ ...data }==>', { ...data })
}
// 删除分类
function nodeDel(data) {
  //   console.log('data==>', data.id)
  proxy.$modal
    .confirm('是否确认删除名为"' + data.name + '"的分类?')
    .then(function () {
      delCategory(data.id).then(e => {
        getTreeList()
        proxy.$modal.msgSuccess('删除成功')
      })
    })
    .catch(() => {})
}
// 下移分类
function nodeDown(data) {
  downCategory(data.id).then(e => {
    getTreeList()
    proxy.$modal.msgSuccess('下移成功')
  })
}
// 确认新增修改
function submitForm() {
  proxy.$refs.sortRef.validate(valid => {
    if (valid) {
      if (sortBox.value.title == '新增') {
        addCategory(sortForm.value)
          .then(e => {
            proxy.$modal.msgSuccess('新增成功')
            sortBox.value.open = false
          })
          .then(e => {
            getTreeList()
          })
      } else {
        updateCategory(sortForm.value)
          .then(e => {
            proxy.$modal.msgSuccess('修改成功')
            sortBox.value.open = false
          })
          .then(e => {
            getTreeList()
          })
      }
    }
  })
}
//重置
function cancel() {
  sortBox.value.open = false
  reset()
}

/** 表单重置 */
function reset() {
  sortForm.value = {}
  proxy.resetForm('sortRef')
}

// function handleAvatarSuccess(res, file) {
//   imageUrl.value = URL.createObjectURL(file.raw)
// }
// function beforeAvatarUpload(file) {
//   const isJPG = file.type === 'image/jpeg'
//   const isLt2M = file.size / 1024 / 1024 < 2

//   if (!isJPG) {
//     proxy.$message.error('上传头像图片只能是 JPG 格式!')
//   }
//   if (!isLt2M) {
//     proxy.$message.error('上传头像图片大小不能超过 2MB!')
//   }
//   return isJPG && isLt2M
// }

function handleAdd() {
  goTo('/source/product/productForm', {
    categoryId: queryParams.value.categoryId
  })
}
function handleUpdate() {
  goTo('/source/product/editProduct', { productId: ids.value[0] })
}
function handleDel(row) {
  let rowIds = row.id || ids.value
  console.log('selectArr-->', selectArr.value)
  proxy.$modal
    .confirm(
      '是否确认删除名称为"' + selectArr.value.map(e => e.name) + '"的数据项?'
    )
    .then(function () {
      return delOrdproduct(rowIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
function handleUpload() {}
init()
</script>
<style scoped>
.box-card {
  min-height: 85vh;
}
.box-card-dia {
  min-height: 100%;
}
.custom-tree-node {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.custom-tree-node .node-title {
  flex-grow: 8;
}
.custom-tree-node .node-btn {
  display: none;
  flex-grow: 1;
}
.el-tree-node__content:hover .node-btn {
  display: block;
}
.avatar-uploader:deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:deep(.el-upload:hover) {
  border-color: #409eff;
}
.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: #8c939d;
  width: 178px;
  height: 178px;
}
.avatar-uploader-icon i {
  font-size: 30px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
